package com.bidevalution.business.impl;

import com.bidevalution.business.function.FunctionInitializer;
import com.bidevalution.business.service.BeFunctionDefineService;
import com.bidevalution.business.service.JdbcTemplateService;
import com.bidevalution.dao.entity.BeFunctionDefine;
import com.bidevalution.dao.mapper.BeFunctionDefineMapper;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import lombok.extern.log4j.Log4j2;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Constructor;

@Service
public class BeFunctionDefineServiceImpl implements BeFunctionDefineService{
	@Autowired
	private BeFunctionDefineMapper beFunctionDefineMapper;
	@Autowired
	private JdbcTemplateService jdbcTemplateService;
	private Logger log = Logger.getLogger(getClass());
	/* 加载方法到公式计算器中
	 * 
	 */
	@Override
	public void initialize() {
		for(BeFunctionDefine beFunctionDefine:beFunctionDefineMapper.selectList()){
			AviatorEvaluator.addFunction(createFunction(beFunctionDefine.getComputeClass()));
		}
	}
	public AbstractFunction createFunction(String className) {
		Object instanceObject = null;
		try {
			Class<?> functionClass = Class.forName(className);
			Constructor<?> c = functionClass.getConstructor(FunctionInitializer.class);
			instanceObject =  c.newInstance(new FunctionInitializer(){

				@Override
				public JdbcTemplateService getJdbcTemplateService() {
					return jdbcTemplateService;
				}});
		} catch (Exception e) {
            log.error(e.getMessage(), e);
		}
		return (AbstractFunction) instanceObject;
	}
}
